package com.ruoyi.common.schedule;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@Component
public class DatabaseBackupTask {

    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";
    private static final String DB_NAME = "warehouse";

    private static final String BACKUP_DIR = "E:\\backup\\"; // 确保目录存在

    // 每天早上8点执行（cron表达式：秒 分 时 日 月 周）
    @Scheduled(cron = "0 23 8 * * ?")
    public void backupDatabase() {
        try {
            // 当前时间作为文件名
            String dateStr = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
            String fileName = "db_backup_" + dateStr + ".sql";
            String filePath = BACKUP_DIR + fileName;

            // 创建目录（如不存在）
            File backupFolder = new File(BACKUP_DIR);
            if (!backupFolder.exists()) {
                backupFolder.mkdirs();
            }

            // 构造 mysqldump 命令
            String command = String.format(
                    "cmd /c mysqldump -u%s -p%s %s > \"%s\"",
                    USERNAME, PASSWORD, DB_NAME, filePath
            );

            // 执行命令
            Process process = Runtime.getRuntime().exec(command);
            int exitCode = process.waitFor();

            if (exitCode == 0) {
                System.out.println("✅ 备份成功：" + fileName);
            } else {
                System.err.println("❌ 备份失败，退出码：" + exitCode);
            }

            // 删除一周前的备份
            deleteOldBackups(7);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除指定天数之前的旧备份文件
     */
    private void deleteOldBackups(int daysBefore) {
        File backupFolder = new File(BACKUP_DIR);
        if (!backupFolder.exists() || !backupFolder.isDirectory()) return;

        File[] files = backupFolder.listFiles((dir, name) -> name.endsWith(".sql"));
        if (files == null) return;

        long now = System.currentTimeMillis();
        long expirationTime = daysBefore * 24L * 60 * 60 * 1000;

        for (File file : files) {
            long diff = now - file.lastModified();
            if (diff >= expirationTime) {
                if (file.delete()) {
                    System.out.println("🗑️ 已删除过期备份：" + file.getName());
                }
            }
        }
    }
}
